import java.net.*;
import java.beans.Expression;
import java.io.*;
import java.security.*;

import javax.crypto.*;
import javax.crypto.spec.*;

import java.security.spec.*;

import javax.crypto.interfaces.*;

import java.security.interfaces.*;
import java.math.*;
public class ClientSend {
    public static void main(String srgs[]) throws Exception {
        try
        {
            // 1、创建客户端Socket，指定服务器地址和端口
            Socket socket=new Socket("127.0.0.1",5330);
            System.out.println("客户端成功启动，等待客户端呼叫");
            // 2、获取输出流，向服务器端发送信息
            // 向本机的10001端口发出客户请求
            System.out.println("请输入中缀表达式：");
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            // 由系统标准输入设备构造BufferedReader对象
            PrintWriter write = new PrintWriter(socket.getOutputStream());
            // 由Socket对象得到输出流，并构造PrintWriter对象
            //3、获取输入流，并读取服务器端的响应信息
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            // 由Socket对象得到输入流，并构造相应的BufferedReader对象
            String readline, infix, expression;
            readline = br.readLine(); // 从系统标准输入读入一字符串
            MyBC theTrans = new MyBC(readline);
            infix = theTrans.doTrans();
            StringBuilder newInfix = new StringBuilder(infix.replace(" ",""));
            for (int i = 1; i < infix.length()+(i+1)/2 ; i=i+2) {
                newInfix.insert(i," ");
            }
            System.out.println("后缀表达式：" + newInfix);
            expression=newInfix.toString();

            FileInputStream f=new FileInputStream("key1.dat");
            ObjectInputStream b=new ObjectInputStream(f);
            Key k=(Key)b.readObject();
            Cipher cp=Cipher.getInstance("DESede");
            cp.init(Cipher.ENCRYPT_MODE, k);
            byte ptext[]=expression.getBytes("UTF-8");
            byte ctext[]=cp.doFinal(ptext);
            String Str=new String(ctext,"ISO-8859-1");
            while (!readline.equals("end")) {
                // 若从标准输入读入的字符串为 "end"则停止循环
                System.out.println("加密后的信息:" + Str);
                // 在系统标准输出上打印读入的字符串
                write.println(Str);
                // 将从系统标准输入读入的字符串输出到Server
                write.flush();
                // 刷新输出流，使Server马上收到该字符串
                System.out.println("服务器发来的信息:" + in.readLine());
                // 从Server读入一字符串，并打印到标准输出上
                readline = br.readLine(); // 从系统标准输入读入一字符串
            } // 继续循环
            //4、关闭资源
            write.close(); // 关闭Socket输出流
            in.close(); // 关闭Socket输入流
            socket.close(); // 关闭Socket
        }
        catch (Exception e)
        {
            System.out.println(e);//输出异常
        }
        finally
        {

        }

    }
}
